package dk.nordahl.btremote;

import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Touchpad extends Activity {

	private View touchpad;
	private OutputStream OPS;
	private BTRemote btr;
	private String cmd;
	private Button leftClick;
	private Button rightClick;
	
	protected void onCreate(android.os.Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.touchpad);
		btr = (BTRemote)getApplication();
		OPS = btr.getOPS();
		
		leftClick = (Button)findViewById(R.id.btnLeftClick);
		rightClick = (Button)findViewById(R.id.btnRightClick);
		
		touchpad = (View)findViewById(R.id.touchView);
		
		leftClick.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				moveCursor("leftClick\n");
				
			}
		});
		rightClick.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				moveCursor("rightClick\n");
				
			}
		});
		touchpad.setOnTouchListener(new View.OnTouchListener() {
	        public boolean onTouch(View v, MotionEvent event) {
	            if(event.getAction()==MotionEvent.ACTION_DOWN){

	            }

	            if(event.getAction() == MotionEvent.ACTION_MOVE)
	            {
	            	String xps = "X: "+(event.getX());
	            	String yps = "Y: "+(event.getY());

	                
	            	cmd  = xps + " " + yps + "\n";	            	
	            	moveCursor(cmd);

	            }
	           
	            return true;
	        }
	    });	
	}
	private void moveCursor(String command)
	{
			byte[] cmd = command.getBytes();
			try 
			{
			    OPS.write(cmd);
			}
			catch (IOException e){
				
				Log.e("Command error", command + " could not be executed");
			}
			catch(NullPointerException e)
			{
				e.printStackTrace();
			}
		}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.btremote_main, menu);
		
		menu.getItem(1).setVisible(false);
		return super.onCreateOptionsMenu(menu);
	}
	public boolean onOptionsItemSelected(MenuItem item) {	
		
		switch(item.getItemId())
		{
			case R.id.device_menu:
			finish();
				return true;
			case R.id.command_menu:
				
			try {
				btr.getBtSocket().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				finish();
				Intent startCommand= new Intent(this, Command.class);
				startActivity(startCommand);
				return true;

			default:
				return super.onOptionsItemSelected(item);
		}
	}
}

